# -*- coding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution
#    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

from osv import fields, osv, orm
import tools
import logging
import addons

class res_company(osv.osv):
    _name = "res.company"
    _description = '组织架构'
    _inherit = 'res.company'
    _order = 'name'
    
    def name_get(self, cr, uid, ids, context=None):
        if context is None:
            context = {}
        if not ids:
            return []
        reads = self.read(cr, uid, ids, ['name','parent_id'], context=context)
        res = []
        for record in reads:
            name = record['name']
            if record['parent_id']:
                name = record['parent_id'][1]+name
            res.append((record['id'], name))
        return res

    def _full_name_get_fnc(self, cr, uid, ids, prop, unknow_none, context=None):
        res = self.name_get(cr, uid, ids, context=context)
        return dict(res)
        
    _columns = {
        'name': fields.char('单位名称', size=128, required=True),
        'parent_id': fields.many2one('res.company', '上级单位', select=True),
        'child_ids': fields.one2many('res.company', 'parent_id', '下属单位', readonly=True),
        'complete_name': fields.function(_full_name_get_fnc, type="char", string='全称'),
    }        

class village_resident_move(osv.osv):
    """户籍迁移"""
    _name = "village.resident.move"
    _description = "户籍迁移"
    _columns = {
        'resident': fields.many2one('village.resident', '迁移人', required = True),
        'company_id': fields.related('resident', 'company_id', type='many2one', relation='res.company', string='所属单位', store=False),
        'direction': fields.selection([('in', '迁入'), ('out', '迁出')], '迁入/出', required = True),
        'reason': fields.char('迁移原因', size=50, required = True),
        'move_date': fields.date('迁移时间', size=12, required = True),
        'move_location': fields.char('迁移地', size=50, required = True)
    }
    
    _defaults = {
        'company_id': lambda self, cr, uid, c: self.pool.get('res.users').browse(cr, uid, uid, c).company_id.id,
    }
    
class village_resident_address(osv.osv):
    """户籍地址"""
    
    _name = "village.resident.address"
    _description = "village resident address"
    
    def name_get(self, cr, uid, ids, context=None):
        if not ids:
            return []
        reads = self.browse(cr, uid, ids, context=context)
        res = []
        for record in reads:
            name = record.name
            if record.company_id:
                name = record.company_id.complete_name + name
            res.append((record.id, name))
        return res

    def _name_get_fnc(self, cr, uid, ids, prop, unknow_none, context=None):
        res = self.name_get(cr, uid, ids, context=context)
        return dict(res)
        
    _columns = {
        'company_id': fields.many2one('res.company', '所属单位', required = True, readonly=True),
        'complete_name': fields.function(_name_get_fnc, type="char", string='名称'),        
        'name': fields.char('门牌号', size = 50, required = True)
    }
    
    _defaults = {
        'company_id': lambda self, cr, uid, c: self.pool.get('res.users').browse(cr, uid, uid, c).company_id.id,
        }

class village_resident_enum(orm.Model):  
    _name = "village.resident.enum"
    _description = "枚举"
    _columns = {
        'name': fields.char('名称', size=50, required=True)
    }
        
class village_resident_relationship(osv.osv):
    """与户主关系"""
    _name = "village.resident.relationship"
    _description = "与户主关系"
    _columns = {
        'name': fields.char('名称', size=50, required=True)
    }    
    
class village_resident_background(osv.osv):
    """政治面貌"""
    _name = "village.resident.background"
    _description = "政治面貌"
    _inherit = "village.resident.enum"
    
class village_resident_residence_type(osv.osv):
    """居住类型"""
    _name = "village.resident.residence.type"
    _description = "居住类型"
    _inherit = "village.resident.enum"
    
class village_resident_education_level(osv.osv):
    """文化程度"""
    _name = "village.resident.education.level"
    _description = "文化程度"
    _inherit = "village.resident.enum"
    
class village_resident_nation(osv.osv):
    """民族"""
    _name = "village.resident.nation"
    _description = "民族"
    _inherit = "village.resident.enum"
    
class village_resident_marital(osv.osv):
    """婚姻状况"""
    _name = "village.resident.marital"
    _description = "婚姻状况"
    _columns = {
        'name': fields.char('名称', size=50, required=True)
    }    
        
class village_resident_disability_type(osv.osv):
    """残疾类别"""
    _name = "village.resident.disability.type"
    _description = "残疾类别"
    _inherit = "village.resident.enum"
    
class village_resident(osv.osv):
    """户籍"""
    _name = "village.resident"
    _description = "户籍"
    _order = 'householder_address, householder_name, relationship'
    
    def _find_move_history_fnc(self, cr, uid, ids, name, args, context=None):
        res = {}
        for resident in self.browse(cr, uid, ids, context=context):
            move_objs = self.get_pool("village.resident.move").browse(cr, uid, resident.move_history_ids, context=context)
            moves = []
            for move in move_objs:
                
                if move.direction == '迁入':
                    moves.append('%s，因 %s由%s迁入' % (move.move_date, move.reason, move.move_location))
                else:
                    moves.append('%s，因 %s迁出到%s' % (move.move_date, move.reason, move.move_location))
            
            if moves:
                res[resident.id] = "/r/n".join(moves)  
            else:
                res[resident.id] = ""
        return res
    
    def _get_householder_name_fnc(self, cr, uid, ids, name, args, context=None):
        res = {}
        for resident in self.browse(cr, uid, ids, context=context):
            
            if resident.is_householder:
                res[resident.id] = resident.name
            elif resident.householder:
                res[resident.id] = resident.householder.name
            else:
                res[resident.id] = ""
        return res
        
    _columns = {
        'name': fields.char('姓名', size=10, required=True),
        'company_id': fields.many2one('res.company', '所属单位', required=True, readonly=True),
        'is_householder': fields.boolean('本人是户主'),
        'householder': fields.many2one('village.resident', '户主'),
        'householder_name': fields.function(_get_householder_name_fnc, '户主姓名', type='char', store=True),
        'relationship': fields.many2one('village.resident.relationship', '与户主关系'),
        #'householder_name': fields.many2one('village.people', '户主'),
        'gender': fields.selection([('male', '男'),('female', '女')], '性别', required=True),
        'identification_id': fields.char('身份证号', size=18, required=True),
        'photo': fields.binary('照片'),
        'team': fields.char('组别', size=10, required=True, help='格式：01'),        
        'birthday': fields.char('出生日期', size=10, help='格式如：1980-01-01'),
        'householder_address': fields.many2one('village.resident.address', '户口所在地'),
#        'householder_address': fields.char('户口所在地', size=20, help='地址不用输入镇村信息'),
        #'full_householder_address': fields.char('户口所在地', size=20, help='地址不用输入镇村信息'),
        'address_home': fields.char('目前住址', size=50),
        'phone': fields.char('联系电话', size=32, readonly=False),
        'mobile_phone': fields.char('手机', size=32, readonly=False),
        'residence_type': fields.many2one('village.resident.residence.type', '居住类型'),
        'education_level': fields.many2one('village.resident.education.level', '文化程度'),
        'nation': fields.many2one('village.resident.nation', '民族'),
        'background': fields.many2one('village.resident.background', '政治面貌'),
        'native_place': fields.char('籍贯', size=50),
        'marital': fields.many2one('village.resident.marital', '婚姻状况'),
        'work_location': fields.char('工作单位', size=32),
        'is_basic_living': fields.boolean('是否低保'),
        'is_village_treatment': fields.boolean('是否享受村待遇'),
        'has_citizen_insurance': fields.boolean('是否城保'),
        'has_village_insurance': fields.boolean('是否农村养老保险'),
        'is_physical_disability': fields.boolean('是否残疾'),
        'physical_disability_type': fields.many2one('village.resident.disability.type', '残疾类别'),
        'notes': fields.text('备注'),
#        'move_history_ids': fields.one2many('village.resident.move', 'resident', readonly=True),
#        'move_history': fields.function(_find_move_history_fnc, string='迁入/迁出历史', readonly=True, type="char" ),
        'move_in_date': fields.date('迁入日期', required=True),
        'move_in_reason': fields.char('迁入原因', size=50, required=True),
        'move_out_date': fields.date('迁出日期', readonly=True),
        'move_out_reason': fields.char('迁出原因', size=50, readonly=True),
        'state': fields.selection([('normal','在册'), ('moved_out', '已迁出')], '状态', readonly=True),
    }
    
    def _get_photo(self, cr, uid, context=None):
        photo_path = addons.get_module_resource('hr','images','photo.png')
        return open(photo_path, 'rb').read().encode('base64')
    
    def _get_default_residence_type(self, cr, uid, context=None):
        photo_path = addons.get_module_resource('hr','images','photo.png')
        return open(photo_path, 'rb').read().encode('base64')
    
    def _get_photo(self, cr, uid, context=None):
        photo_path = addons.get_module_resource('hr','images','photo.png')
        return open(photo_path, 'rb').read().encode('base64')

    _defaults = {
        'company_id': lambda self, cr, uid, c: self.pool.get('res.users').browse(cr, uid, uid, c).company_id.id,
        'is_householder': False,
        'photo': _get_photo,
        #'residence_type': lambda self, cr, uid, c: self.pool.get('village.resident.residence.type').browse(cr, uid, uid, c).company_id.id,
        #'education_level': '本科',
        #'nation': '汉族',
        #'background': '清白',
        #'marital': '未婚',
        'is_basic_living': True,
        'is_village_treatment': True,
        'has_citizen_insurance': False,
        'has_village_insurance': True,
        'is_physical_disability': False,
        'state': 'normal',
        'move_in_date': fields.date.context_today,
    }
    
    def on_householder_change(self, cr, uid, ids, is_householder, householder, context=None):
        
        result = {}
        if (not is_householder) and householder:
            householder_obj = self.browse(cr, uid, householder)
            result['team'] = householder_obj.team
            result['householder_address'] = householder_obj.householder_address.id
            
        return {'value': result}
    
    def on_is_householder_change(self, cr, uid, ids, is_householder, householder, context=None):
        """是否是户主改变"""
        result = {}
        domain={'relationship': [('name', '!=', u'户主')]}
        if is_householder:
            
            result['householder'] = None
            relationship_obj = self.pool.get('village.resident.relationship')
            relationships = relationship_obj.name_search(cr, uid, name=u'户主', operator='=')
            result['relationship'] = (relationships and relationships[0][0]) or None
            
            domain={'relationship': [('name', '=', u'户主')]}
        elif householder:
            householder_obj = self.browse(cr, uid, householder)
            result['team'] = householder_obj.team
            result['householder_address'] = householder_obj.householder_address.id
            result['relationship'] = None
            
        return {'value': result, 'domain': domain}
        
class village_resident_query(orm.Model):
    """户籍查询"""
    _name = "village.resident.query"
    _inherit = "village.resident"
    _auto = False
        
    def init(self, cr):
        tools.drop_view_if_exists(cr, 'village_resident_query')
        cr.execute("""
            create or replace view village_resident_query as (
                select *
                from
                    village_resident
                order by householder_address, householder_name, relationship
            )
        """)

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
